<template>
  <div
    class="attach-preview h100 w100"
    v-loading="loading"
    element-loading-text="拼命加载中"
    element-loading-background="rgba(255, 255, 255, 1)"
  >
    <pdf-viewer
      ref="myPdfComponent"
      class="attach-preview--pdf"
      v-if="showType == 'pdf'"
      :src="preurl"
      @loadSuccess="loadSuccess"
      @loadFail="loadFail"
    />
    <div class="h100 w100 attach-preview--html" v-else-if="showType == 'html'" v-html="htmlText"></div>
    <video
      class="h100 w100 attach-preview--video"
      v-else-if="showType == 'video'"
      autoplay="autoplay"
      controls
      preload="auto"
      :src="preurl"
    ></video>
    <img
      v-else-if="showType == 'imge'"
      ref="imgView"
      class="imgView"
    />
    <div v-else class="loading">
      <i class="el-icon-picture-outline"></i>
    </div>
  </div>
</template>

<script>
import pdfViewer from "@/components/pdfViewer/index";
import { downloadFile } from "@/api/common";
import axios from "axios";
export default {
  props: {
    fileObj: {
      type: Object,
      default: () => {
        return {};
      }
    }
  },
  components: { pdfViewer },
  data() {
    return {
      preurl: "",
      loading: false,
      typeObj: {
        imge: ["jpg", "jpeg", "gif", "bmp", "png"],
        pdf: ["pdf"],
        video: ["mp4", "m2v", "mkv", "rmvb", "wmv", "avi", "flv", "mov", "m4v"],
        html: ["htm", "html"],
        docx: ["doc", "docx", "docm", "dotx", "dotm"],
        xlsx: ["xls", "xlsx", "xlsm", "xltx", "xltm", "xlsb", "xlam"],
        pptx: ["ppt", "pptx", "pot", "potx", "pptm", "ppsx", "ppsm"]
      },
      previewType: "",
      htmlText: "预览转换中。。。",
      source: null,
      transform: {
        scale: 1,
        deg: 0,
        offsetX: 0,
        offsetY: 0,
        enableTransition: false
      }
    };
  },
  watch: {
    fileObj(val) {
      this.cancel();
      this.init();
    }
  },
  computed: {
    showType() {
      let currentType = "";
      for (const key in this.typeObj) {
        const element = this.typeObj[key];
        if (element.includes(this.previewType)) {
          currentType = key;
        }
      }
      return currentType;
    },
  },
  mounted() {
    this.init();
  },
  methods: {
    async init() {
      this.loading = true;
      this.previewType = "";
      let { attachmentName: name, path, extension, id } = this.fileObj;
      this.source = axios.CancelToken.source();
      let baseUrl = process.env.VUE_APP_BASEURL;
      if (this.showType == "pptx") {
        this.$message.warning("该附件过大，请直接下载查看！");
        return;
      }
      this.preurl =
        process.env.VUE_APP_BASEURL +
        "/eam-common-web/attachment/preview/?fileId=" +
        id;

      this.previewType = extension;
      // debugger
      if (this.showType == "imge") {
        // 图片预览
        let token = localStorage.getItem("GDH_WATER_TOKEN") || "";
        Object.defineProperty(Image.prototype, "authsrc", {
          writable: true,
          enumerable: true,
          configurable: true
        });
        this.$nextTick(() => {
          let imgView = this.$refs.imgView;
          let request = new XMLHttpRequest();
          request.responseType = "blob";
          request.open("get", this.preurl, true);
          //这里带上请求头
          request.setRequestHeader("jwt_token", token);
          request.setRequestHeader(
            "DYNAMIC_DATA_SOURCE",
            localStorage.getItem("currDs")
          );
          request.onreadystatechange = e => {
            if (
              request.readyState == XMLHttpRequest.DONE &&
              request.status == 200
            ) {
              imgView.src = URL.createObjectURL(request.response);
              imgView.onload = () => {
                this.loading = false;
                URL.revokeObjectURL(imgView.src);
              };
            }
          };
          request.send(null);
        });
      } else if (this.previewType == "html") {
        let res = await this.$utils.downloadFile(id, name);
        if (res) {
          const blob = new Blob([res]);
          this.htmlText = "";
          var reader = new FileReader();
          reader.readAsText(blob);
          reader.onload = () => {
            this.loading = false;
            this.htmlText = reader.result; //内容就在这里
          };
        }
      }
      return;
    },
    loadSuccess() {
      this.loading = false;
    },
    loadFail() {
      this.loading = false;
    },
    cancel() {
      if (this.source) {
        this.source.cancel("取消");
      }
    },
  }
};
</script>

<style lang="less">
.attach-preview {
  background-color: #fcfcfc;
  display: flex;
  justify-content: center;
  position: relative;
  overflow: auto;
  align-items: flex-start;
  padding: 10px;
  .loading i {
    font-size: 60px;
    color: #9b9b9b;
  }
  .imgView {
    margin: 0 auto;
    max-width: 100%;
    max-height: 100%;
  }
}
.attach-preview:hover {
  cursor: pointer;
}
</style>